package _算法思维系列._回溯算法;


import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: 吕庆龙
 * @Date: 2020/6/20 18:20
 * <p>
 * 功能描述:
 */
public class Summary_0046 {

    List<List<Integer>> res = new LinkedList<>();

    /* 主函数，输入一组不重复的数字，返回它们的全排列 */
    List<List<Integer>> permute1(int[] nums) {
        // 记录「路径」
        LinkedList<Integer> track = new LinkedList<>();
        backtrack(nums, track);
        return res;
    }

    void backtrack(int[] nums, LinkedList<Integer> track) {
        // 触发结束条件
        if (track.size() == nums.length) {
            res.add(new LinkedList(track));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            // 排除不合法的选择
            if (track.contains(nums[i]))
                continue;
            // 做选择
            track.add(nums[i]);
            // 进入下一层决策树
            backtrack(nums, track);
            // 取消选择
            track.removeLast();
        }
    }


    /*------------------------------------------------------------------------------------*/

    /**
     * https://leetcode-cn.com/problems/permutations/solution/hui-su-suan-fa-python-dai-ma-java-dai-ma-by-liweiw/
     */

    List<List<Integer>> res1 = new LinkedList<>();
    int len;
    boolean[] used;

    public List<List<Integer>> permute(int[] nums) {
        // 首先是特判
        len = nums.length;

        if (len == 0) {
            return res1;
        }

        used = new boolean[len];
        List<Integer> path = new ArrayList<>();

        dfs(nums, path);
        return res1;
    }

    private void dfs(int[] nums, List<Integer> path) {
        if (path.size() == len) {
            res1.add(new ArrayList<>(path));
            return;
        }

        for (int i = 0; i < len; i++) {
            if (!used[i]) {
                //决策树上进行选择
                path.add(nums[i]);
                used[i] = true;

                dfs(nums, path);
                //状态重置，撤销选择
                used[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }

    //这个函数也可以这样写
//    private void dfs(int[] nums, List<Integer> path) {
//        if (path.size() == len) {
//            res1.add(new ArrayList<>(path));
//            return;
//        }
//
//        for (int i = 0; i < len; i++) {
//            if (used[i])
//                continue;
//            //决策树上进行选择
//            path.add(nums[i]);
//            used[i] = true;
//
//            dfs(nums, path);
//            //状态重置，撤销选择
//            used[i] = false;
//            path.remove(path.size() - 1);
//
//        }
//    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        Summary_0046 solution = new Summary_0046();
        List<List<Integer>> lists = solution.permute(nums);
        System.out.println(lists);
    }


}
